const {
	Api
} = require('@/utils/api/api.js');
import {
	RetCodeMsg,
	CodeMsg
} from './errorCode.js'
// 封装登录逻辑的函数
// 封装 showToast 函数
function showToast(title, icon = 'none') {
	uni.showToast({
		title: title,
		icon: icon
	});
}

// 封装登录逻辑的函数
function deviceLogin(device, callback) {
	let tryTokenCount = 0;
	let tryCount = 0;
	let tryTimeOutCount = 0;

	uni.showLoading({
		title: '加载中...',
		mask: true
	});

	const data = {
		encryptType: 'DISABLE',
		LoginType: 'DVRIP-Web',
		UserName: device.devUserName,
		PassWord: device.devPassWord,
		Name: 'generalinfo',
		KeepaliveTime: 30
	};

	if (device.adminToken) {
		data.LoginToken = device.adminToken;
		data.encryptType = 'TOKEN';
	}

	const token = device.token;
 //    setTimeout(()=>{
	// 	uni.hideLoading();
	// },1000)
	function performLogin() {
		getApp().globalData.api.deviceLogin(data, token, (result) => {
			uni.hideLoading();
			if (result.data.code === 2000) {
				let Ret = result.data.data.Ret
				if (Ret === 100 || Ret === 104) {
					callback(result.data);
				} else if (Ret === 137) {
					tryTokenCount++
					if (tryTokenCount > 1) {
						showToast(RetCodeMsg[Ret] || result.data.data.RetMsg);
					}
				} else {
					showToast(RetCodeMsg[Ret] || result.data.data.RetMsg);
				}
			} else if (result.data.code === 4000) {
				showToast(result.data.msg);
			} else if (result.data.code == 4103) {
				tryCount++
				if (tryCount <= 1) {
					performLogin();
				}
			} else if (result.data.code == 4118) {
				tryTimeOutCount++
				if (tryTimeOutCount < 4) {
					performLogin();
				} else {
					showToast(CodeMsg[result.data.code] || result.data.msg);
				}
			} else if (result.data.code == 4120 || result.data.code == 4101) {
				// uni.showModal({
				// 	content: '设备已进入深度休眠状态，请手动唤醒后继续访问设备',
				// 	showCancel: false,
				// 	confirmColor: '#FF0025',
				// 	confirmText: '确定',
				// 	success: (res) => {
				// 		callback('back');
				// 	}
				// });
				callback(result.data)
			} else {
				showToast(CodeMsg[result.data.code] || result.data.msg);
			}
		});
	}
	performLogin();
}

export default deviceLogin;